package com.lhg.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lhg.entity.Info;
import com.lhg.entity.Vo.InfoVo;
import com.lhg.mapper.InfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class InfoService {
    @Autowired
    private InfoMapper infoMapper;

    public void insertInfo(Info info) {
        infoMapper.insertInfo(info);
    }

    public Info extractInfo(String response) {
        ObjectMapper mapper = new ObjectMapper();
        // 创建JobInfo实例并设置属性值
        Info jobInfo = new Info();
        try {
            // 解析外部JSON
            JsonNode rootNode = mapper.readTree(response);

            // 获取data字段中的content字段，并去除转义字符
            String contentString = rootNode.get("data").get("content").asText().replaceAll("\\\\n", "").replaceAll("\\\\\"", "\"");

            // 解析content字段的JSON
            JsonNode contentNode = mapper.readTree(contentString);

            // 设置字符串类型的属性
            jobInfo.setCompany(contentNode.get("company").asText());
            jobInfo.setJobTitle(contentNode.get("jobTitle").asText());
            jobInfo.setWebsite(contentNode.get("website").asText());
            jobInfo.setBase(contentNode.get("base").asText());
            jobInfo.setSize(contentNode.get("size").asText());
            jobInfo.setType(contentNode.get("type").asText());
            jobInfo.setIndustry(contentNode.get("industry").asText());

            // 设置日期类型的属性，假设字段存在并且格式正确
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 或者您需要的日期格式

            String examTimeStr = contentNode.get("examTime").asText();
            try {
                Date examTime = sdf.parse(examTimeStr);
                jobInfo.setExamTime(sdf.format(examTime));
            } catch (ParseException e) {
                // 处理日期解析异常
//                e.printStackTrace();
                // 可能的处理方式：设置默认值、记录错误、返回错误信息等
            }

            String interviewTimeStr = contentNode.get("interviewTime").asText();
            try {
                Date interviewTime = sdf.parse(interviewTimeStr);
                jobInfo.setInterviewTime(sdf.format(interviewTime));
            } catch (ParseException e) {
                // 处理日期解析异常
//                e.printStackTrace();
                // 可能的处理方式：设置默认值、记录错误、返回错误信息等
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return jobInfo;
    }

    public PageInfo<Info> selectPage(String query, Integer userId, Integer currentPage, Integer pageSize) {
        PageHelper.startPage(currentPage, pageSize);
        List<Info> items = infoMapper.selectAll(query, userId);
        return PageInfo.of(items);
    }

    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            infoMapper.deleteById(id);
        }
    }

    public Info selectById(Integer editId) {
        return infoMapper.selectById(editId);
    }

    public void deleteById(Integer editId) {
        infoMapper.deleteById(editId);
    }

    public List<InfoVo> calendarMake(Integer userId) throws ParseException {
        List<Info> infoList = infoMapper.selectByUserId(userId);
        List<InfoVo> infoVoList = new LinkedList<>();
//        Date dateToCompare = new Date(); // 或者其他你想要的日期
        // 获取今天的日期并设置为0点
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date todayMidnight = calendar.getTime();

        // 创建SimpleDateFormat对象用于格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 或者您需要的日期格式
        SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm");

        for(Info info : infoList){
            if((info.getExamTime()!=null && !info.getExamTime().isEmpty() && sdf.parse(info.getExamTime()).after(todayMidnight)) ||
                    info.getInterviewTime()!=null && !info.getInterviewTime().isEmpty() && sdf.parse(info.getInterviewTime()).after(todayMidnight)){
                InfoVo infoVo = new InfoVo();
                infoVo.setId(info.getId());
                infoVo.setCompany(info.getCompany());
                infoVo.setJobTitle(info.getJobTitle());
                infoVo.setWebsite(info.getWebsite());
                infoVo.setIntent(info.getPriority());
//                System.out.println("time: "+info.getExamTime()+"nullcheck: "+(info.getPriority()==null));
                if(info.getExamTime()!=null && !info.getExamTime().isEmpty() && sdf.parse(info.getExamTime()).after(todayMidnight)){
                    infoVo.setType("笔试");
                    infoVo.setStart(sdfDate.format(sdfDate.parse(info.getExamTime())));
                    infoVo.setStartTime(sdfTime.format(sdf.parse(info.getExamTime())));
                }
                if(info.getInterviewTime()!=null &&  !info.getInterviewTime().isEmpty() && sdf.parse(info.getInterviewTime()).after(todayMidnight)){
                    infoVo.setType("面试");
                    infoVo.setStart(sdfDate.format(sdfDate.parse(info.getInterviewTime())));
                    infoVo.setStartTime(sdfTime.format(sdf.parse(info.getInterviewTime())));
                }
                infoVo.setUserId(userId);
                infoVoList.add(infoVo);
            }
        }
        return infoVoList;
    }

    public PageInfo<InfoVo> searchExam(InfoVo infoVo, Integer userId, Integer currentPage, Integer pageSize) throws ParseException {
        PageHelper.startPage(currentPage, pageSize);
        List<Info> infoList = infoMapper.selectExam(infoVo, userId);
        List<InfoVo> infoVoList = new LinkedList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm");
        for(Info info : infoList){
            InfoVo vo = new InfoVo();
            vo.setCompany(info.getCompany());
            vo.setJobTitle(info.getJobTitle());
            vo.setWebsite(info.getWebsite());
            vo.setIntent(info.getPriority());
            vo.setStart(sdfDate.format(sdfDate.parse(info.getExamTime())));
            vo.setStartTime(sdfTime.format(sdf.parse(info.getExamTime())));
            vo.setNotes(info.getNotes());
            infoVoList.add(vo);
        }
        return PageInfo.of(infoVoList);
    }

    public String searchExamContent(InfoVo infoVo, Integer userId) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 获取今天的日期时间，并设置为0点
        LocalDateTime todayMidnight = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
        String todayMidnightString = todayMidnight.format(formatter);
        // 获取明天的日期时间，并设置为0点
        LocalDateTime tomorrowMidnight = todayMidnight.plusDays(1).truncatedTo(ChronoUnit.DAYS);
        String tomorrowMidnightString = tomorrowMidnight.format(formatter);
        // 获取未来第七天的日期时间，并设置为0点
        LocalDateTime sevenDaysLaterMidnight = todayMidnight.plusDays(7).withHour(0).withMinute(0).withSecond(0).withNano(0);
        String sevenDaysLaterMidnightString = sevenDaysLaterMidnight.format(formatter);
        infoVo.setStart(todayMidnightString);
        infoVo.setEnd(tomorrowMidnightString);
        List<Info> infoList = infoMapper.selectExam(infoVo,userId);
        // 使用Java 8的Stream API将List转换为字符串
        String todayString = infoList.stream()
                .map(Object::toString) // 或者直接使用 info -> info.toString()
                .collect(Collectors.joining(", ")); // 使用逗号加空格作为分隔符
        infoVo.setStart(todayMidnightString);
        infoVo.setEnd(sevenDaysLaterMidnightString);
        infoList = infoMapper.selectExam(infoVo,userId);
        String futureString = infoList.stream()
                .map(Object::toString) // 或者直接使用 info -> info.toString()
                .collect(Collectors.joining(", ")); // 使用逗号加空格作为分隔符
        System.out.println(futureString);
        return "今日到期笔试信息: "+todayString+"; 未来一周到期笔试信息: "+futureString+"。";
    }
    /*
    *     private Integer id;
        private String company;
        private String jobTitle;
        private String website;
        private String intent;
        private String type;
        private Date start;
        private String startTime;
        private Integer userId;*/
    public PageInfo<InfoVo> searchInterview(InfoVo infoVo, Integer userId, Integer currentPage, Integer pageSize) throws ParseException {
        PageHelper.startPage(currentPage, pageSize);
        List<Info> infoList = infoMapper.selectInterview(infoVo, userId);
        List<InfoVo> infoVoList = new LinkedList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm");
        for(Info info : infoList){
            InfoVo vo = new InfoVo();
            vo.setCompany(info.getCompany());
            vo.setJobTitle(info.getJobTitle());
            vo.setWebsite(info.getWebsite());
            vo.setIntent(info.getPriority());
            vo.setStart(sdfDate.format(sdfDate.parse(info.getInterviewTime())));
            vo.setStartTime(sdfTime.format(sdf.parse(info.getInterviewTime())));
            vo.setNotes(info.getNotes());
            vo.setInterviewRounds(info.getInterviewRounds());
            infoVoList.add(vo);
        }
        return PageInfo.of(infoVoList);
    }

    public String searchTodayInterview(InfoVo infoVo, Integer userId) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 获取今天的日期时间，并设置为0点
        LocalDateTime todayMidnight = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
        String todayMidnightString = todayMidnight.format(formatter);
        // 获取明天的日期时间，并设置为0点
        LocalDateTime tomorrowMidnight = todayMidnight.plusDays(1).truncatedTo(ChronoUnit.DAYS);
        String tomorrowMidnightString = tomorrowMidnight.format(formatter);
        infoVo.setStart(todayMidnightString);
        infoVo.setEnd(tomorrowMidnightString);
        List<Info> infoList = infoMapper.selectInterview(infoVo,userId);
        // 使用Java 8的Stream API将List转换为字符串
        String todayString = infoList.stream()
                .map(info -> "公司=" + info.getCompany() + ", 岗位=" + info.getJobTitle()
                        + ", 我的偏好程度=" + info.getPriority()+ ", 面试轮次=" + info.getInterviewRounds()
                        ).collect(Collectors.joining("; "));
        return "今日到期面试信息: "+todayString+"。";
    }

    public String searchUpcomingInterview(InfoVo infoVo, Integer userId) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 获取今天的日期时间，并设置为0点
        LocalDateTime todayMidnight = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
        String todayMidnightString = todayMidnight.format(formatter);
        // 获取未来第七天的日期时间，并设置为0点
        LocalDateTime sevenDaysLaterMidnight = todayMidnight.plusDays(7).withHour(0).withMinute(0).withSecond(0).withNano(0);
        String sevenDaysLaterMidnightString = sevenDaysLaterMidnight.format(formatter);
        infoVo.setStart(todayMidnightString);
        infoVo.setEnd(sevenDaysLaterMidnightString);
        List<Info> infoList = infoMapper.selectInterview(infoVo,userId);
        String upcomingString = infoList.stream()
                .map(info -> "公司=" + info.getCompany() + ", 岗位=" + info.getJobTitle()
                        + ", 我的偏好程度=" + info.getPriority()+ ", 面试轮次=" + info.getInterviewRounds()
                ).collect(Collectors.joining("; "));
        return "未来一周到期面试信息: "+upcomingString+"。";
    }

    public List<Info> selectOffers(Integer userId) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 获取今天的日期时间，并设置为0点
        LocalDateTime todayMidnight = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
        String todayMidnightString = todayMidnight.format(formatter);
        return infoMapper.selectOffers(todayMidnightString,userId);
    }
}
